package org.yscz.config;

import com.yscz.bs.lib.InquestControlGrpc;
import com.yscz.bs.lib.InquestControlOuterClass;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.yscz.common.ViewConfig;
import org.yscz.entity.RoomBean;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 流媒体相关
 */
public class InquestConfig {

    private static Logger logger = LoggerFactory.getLogger(InquestConfig.class);

    private final ManagedChannel channel;
    private final InquestControlGrpc.InquestControlBlockingStub blockingStub;


    public InquestConfig(String grpcIp, int grpcPort) {
        channel = ManagedChannelBuilder.forAddress(grpcIp, grpcPort)
                .usePlaintext(true)
                .build();
        blockingStub = InquestControlGrpc.newBlockingStub(channel);
    }

    public void shutdown() throws InterruptedException {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }

    /**
     * 通知算法
     */
    public InquestControlOuterClass.StartReply startInquest(RoomBean roomBean) {
        logger.info("InquestConfig.startInquest start");
        InquestControlOuterClass.StartReply startReply = null;
        InquestControlOuterClass.StartRequest startRequest = InquestControlOuterClass.StartRequest.newBuilder()
                .setDrainage(roomBean.getStreamWay() > 0 ? 1 : 0)
                .setNeutralFace(0 != roomBean.getNeutralFace())
                .setUsbDev(roomBean.getUsbDev() == null ? "" : String.valueOf(roomBean.getUsbDev()))
                .setAudioDev(roomBean.getAudioDev() == null ? "" : String.valueOf(roomBean.getAudioDev()))
                .setUrl(roomBean.getCameraUrl() == null ? "" : String.valueOf(roomBean.getCameraUrl()))
                .setAudioUrl(roomBean.getAudioUrl() == null ? "" : String.valueOf(roomBean.getAudioUrl()))
                .setSsUrl(roomBean.getSsUrl() == null ? "" : String.valueOf(roomBean.getSsUrl()))
                .setRoomId(roomBean.getUuid() == null ? "" : String.valueOf(roomBean.getUuid()))
                .setUserId(roomBean.getUserId() == null ? "" : String.valueOf(roomBean.getUserId()))
                .setTrtcRoomName("")
                .setTrtcUserid("")
                .setTrtcUserid2("")
                .setTrtcUsersig("")
                .setTrtcUsersig2("")
                .setTrtcClientid("")
                .setTrtcClientid2("")
                .setTrtcSdkAppId(1)
                .build();
        startReply = blockingStub.startInquest(startRequest);
        logger.info("InquestConfig.startInquest end");
        return startReply;
    }


    public InquestControlOuterClass.TerminateReply terminateInquest(Map<String, Object> param) throws InterruptedException {
        logger.info("InquestConfig.terminateInquest start");
        Integer d = param.get("drainage") == null ? null : Integer.parseInt(param.get("drainage").toString());
        String r = param.get("uuid") == null ? null : String.valueOf(param.get("uuid"));
        String u = param.get("userId") == null ? null : String.valueOf(param.get("userId"));
        String t = param.get("trtcRoomName") == null ? null : String.valueOf(param.get("trtcRoomName"));
        String tt = param.get("trtcClientid") == null ? null : String.valueOf(param.get("trtcClientid"));


        InquestControlOuterClass.TerminateReply terminateReply = null;
        try {
            InquestControlOuterClass.TerminateRequest terminateRequest = InquestControlOuterClass.TerminateRequest.newBuilder()
                    .setDrainage(param.get("drainage") == null ? 1 : Integer.parseInt(param.get("drainage").toString()))
                    .setRoomId(param.get("uuid") == null ? "" : String.valueOf(param.get("uuid")))
                    .setUserId(param.get("userId") == null ? "" : String.valueOf(param.get("userId")))
                    .setTrtcRoomName(param.get("trtcRoomName") == null ? "" : String.valueOf(param.get("trtcRoomName")))
                    .setTrtcClientid(param.get("trtcClientid") == null ? "" : String.valueOf(param.get("trtcClientid")))
                    .build();
            terminateReply = blockingStub.terminateInquest(terminateRequest);
            logger.info("InquestConfig.terminateInquest end");
        } catch (Exception e) {
            logger.error(" InquestConfig.terminateInquest err e: " + e.getMessage());
        }

        return terminateReply;
    }

    public InquestControlOuterClass.GetResultReply getResult() {
        InquestControlOuterClass.GetResultReply getResultReply = null;
        try {
            InquestControlOuterClass.GetResultRequest getResultRequest = InquestControlOuterClass.GetResultRequest.newBuilder().build();
//            logger.info(" InquestConfig.getResult getResultRequest: "+getResultRequest);
            getResultReply = blockingStub.getResult(getResultRequest);
            //logger.info(" InquestConfig.getResult getResultReply: "+getResultReply);
        } catch (Exception e) {
            //只能连接一个客户端
            logger.error(" InquestConfig.getResult err e: " + e.getMessage());
        }

        return getResultReply;
    }


    /**
     * 算法控制
     *
     * @param param
     * @return
     * @throws Exception
     */
    public InquestControlOuterClass.ControlResult algControl(Map<String, Object> param) throws Exception {
        InquestControlOuterClass.ControlResult controlResult = null;
        try {
            logger.info("InquestConfig.algControl param:" + param);
            String roomId = param.get("roomId") == null ? null : param.get("roomId").toString();
            boolean faceRect = param.get("faceRect") != null && (boolean) param.get("faceRect");
            boolean faceLandmark = param.get("faceLandmark") != null && (boolean) param.get("faceLandmark");
            boolean poses = param.get("poses") != null && (boolean) param.get("poses");
            boolean gaze = param.get("gaze") != null && (boolean) param.get("gaze");
            boolean eyes = param.get("eyes") != null && (boolean) param.get("eyes");
            String ssUrl = param.get("ssUrl") == null ? null : param.get("ssUrl").toString();

            InquestControlOuterClass.FlowParam flowParam = InquestControlOuterClass.FlowParam.newBuilder()
                    .setFaceRect(faceRect)
                    .setFaceLandmark(faceLandmark)
                    .setPoses(poses)
                    .setGaze(gaze)
                    .setEyes(eyes)
                    .setSsUrl(ssUrl).build();

            InquestControlOuterClass.ControlParam controlParam = InquestControlOuterClass.ControlParam.newBuilder()
                    .setRoomId(roomId)
                    .setFlowParam(flowParam).build();

            logger.info("InquestConfig.algControl");
            controlResult = blockingStub.algControl(controlParam);
            logger.info("InquestConfig.algControl");
        } catch (Exception e) {
            logger.error(" InquestConfig.algControl err e: " + e.getMessage());
        }
        return controlResult;
    }
}
